using System.Collections.Generic;
using UnityEngine;

public class SegmentMeshBuilder : MeshBuilder
{
   [Header("Mesh Options")]
   public Vector3 point0;
   public Vector3 point1;

   [Min(0)]
   public float width;

   [Min(0)]
   public int trianglesPerRevolution;

   private int c0Index;
   private int c1Index;
   private int p0Index;
   private int q0Index;
   private int triangleCount;

   protected override void Preprocess()
   {
      //triangles in semicircle
      triangleCount = Mathf.CeilToInt(0.5f * trianglesPerRevolution);

      c0Index = 0;
      p0Index = 1;
      c1Index = triangleCount + 2;
      q0Index = triangleCount + 3;
   }

   protected override List<Vector3> CalculateVertices()
   {
      var vertices = new List<Vector3>();

      vertices.AddRange(MeshBuilderUtils.SectorVertices(point0, width / 2, MeshBuilderUtils.Right1, MeshBuilderUtils.Right3, true, triangleCount));
      vertices.AddRange(MeshBuilderUtils.SectorVertices(point1, width / 2, MeshBuilderUtils.Right3, MeshBuilderUtils.Right1, true, triangleCount));

      return vertices;
   }

   protected override List<int> CalculateTriangles()
   {
      var triangles = new List<int>();

      triangles.AddRange(MeshBuilderUtils.SectorTriangles(c0Index, triangleCount, true));
      triangles.AddRange(MeshBuilderUtils.SectorTriangles(c1Index, triangleCount, true));
      triangles.AddRange(MeshBuilderUtils.QuadTriangles(
         p0Index, p0Index + triangleCount,
         q0Index, q0Index + triangleCount));

      return triangles;
   }

   protected override List<Vector2> CalculateUvs(List<Vector3> vertices)
   {
      var uvs = new List<Vector2>();
      var center = Vector2.one / 2;

      uvs.AddRange(MeshBuilderUtils.SectorUvs(center, 0.5f, MeshBuilderUtils.Right1, MeshBuilderUtils.Right3, triangleCount, true));
      uvs.AddRange(MeshBuilderUtils.SectorUvs(center, 0.5f, MeshBuilderUtils.Right3, MeshBuilderUtils.Right1, triangleCount, true));

      return uvs;
   }
}